const mongoose = require('./db');
const Schema = mongoose.Schema;

// 排班模型
const scheduleSchema = new Schema({
    technician: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    title: {
        type: String,
        required: true,
        default: '工作安排'
    },
    start: {
        type: Date,
        required: true
    },
    end: {
        type: Date,
        required: true
    },
    allDay: {
        type: Boolean,
        default: false
    },
    color: {
        type: String,
        default: '#3788d8'
    },
    status: {
        type: String,
        enum: ['scheduled', 'confirmed', 'cancelled', 'completed'],
        default: 'scheduled'
    },
    notes: {
        type: String,
        default: ''
    },
    createdBy: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    updatedBy: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    createTime: {
        type: Date,
        default: Date.now
    },
    updateTime: {
        type: Date,
        default: Date.now
    }
});

// 索引优化
scheduleSchema.index({ technician: 1, start: 1, end: 1 });
scheduleSchema.index({ start: 1, end: 1 });

// 更新时间中间件
scheduleSchema.pre('save', function(next) {
    this.updateTime = new Date();
    next();
});

// 静态方法：获取技师的排班
scheduleSchema.statics.findByTechnician = function(technicianId, startDate, endDate) {
    return this.find({
        technician: technicianId,
        start: { $gte: startDate },
        end: { $lte: endDate }
    }).populate('technician', 'username avatar');
};

// 静态方法：获取日期范围内的排班
scheduleSchema.statics.findByDateRange = function(startDate, endDate) {
    return this.find({
        start: { $gte: startDate },
        end: { $lte: endDate }
    }).populate('technician', 'username avatar skills').sort({ start: 1 });
};

// 静态方法：检查时间冲突
scheduleSchema.statics.checkConflict = function(technicianId, start, end, excludeId = null) {
    const query = {
        technician: technicianId,
        status: { $ne: 'cancelled' },
        $or: [
            { start: { $lt: end }, end: { $gt: start } }
        ]
    };
    
    if (excludeId) {
        query._id = { $ne: excludeId };
    }
    
    return this.findOne(query);
};

module.exports = mongoose.model('Schedule', scheduleSchema);